<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Http\Requests\Setting\PermissionStoreRequest;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class PermissionController extends Controller
{
    public function index(): array
    {
        $list = Permission::query()->get()->toArray();
        return $this->success(data: $list);
    }

    public function getAllPermissionKeys(): array
    {
        return $this->success(Permission::query()->where('type', 0)->pluck('slug')->toArray());
    }

    public function store(PermissionStoreRequest $request): array
    {
        $params = $request->validated();
        $list = $params['permissions'] ?? [];
        unset($params['permissions']);

        $id = Permission::query()->insertGetId([...$params, 'type' => 1]);
        Permission::query()->insert(array_map(function ($v) use ($id) {
            $v['pid'] = $id;
            return $v;
        }, $list));

        return $this->success();
    }

    public function detail(int $id): array
    {
        $data = Permission::query()->find($id)->toArray();
        $data['permissions'] = Permission::query()->where('pid', $data['id'])
            ->where('type', 0)->pluck('slug')->toArray();
        return $this->success($data);
    }

    public function update(int $id, PermissionStoreRequest $request): array
    {
        $params = $request->validated();
        $list = $params['permissions'] ?? [];
        unset($params['permissions']);
        Permission::query()->where('id', $id)->update($params);
        foreach ($list as $item) {
            $permission = Permission::query()->where('slug', $item['slug'])->first();
            if ($permission) {
                if ($permission->pid === $id) {
                    continue;
                }
                $permission->pid = $id;
                $permission->save();
            } else {
                Permission::query()->insert([...$item, 'pid' => $id]);
            }
        }
        return $this->success();
    }

    public function refresh(): array
    {
        foreach (Route::getRoutes()->getRoutes() as $route) {
            $an = $route->getActionName();
            if (str_contains($an, 'App\Http\Controllers') &&
                !str_contains($an, 'AuthController') &&
                !str_contains($an, 'DevController')) {
                $method = $route->methods[0];
                $uri = $route->uri;
                Permission::query()->where('slug', md5($method . $uri))
                    ->update([
                        'name' => $route->getName() ?: '无',
                        'uri' => $uri,
                        'method' => $method,
                    ]);
            }
        }
        return $this->success();
    }
}
